package de.ishuo.netzclubminutecounter;

import java.awt.Color;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.JLabel;

/**
 * A JLabel with animated setText effect.
 * 
 * When setText get called, first fades out the old text
 * then fades in the new text.
 * 
 * @author shuo
 *
 */
public class SetTextWithAnimationLabel extends JLabel {

	

	private static final long serialVersionUID = -9173717932060531192L;
	
	private ExecutorService executor = Executors.newSingleThreadExecutor();

	public SetTextWithAnimationLabel() {}
	
	public SetTextWithAnimationLabel(String string) {
		super(string);
	}

	@Override
	public void setText(final String newText) {
		final Color foreground = getForeground();
		if (foreground == null) {
			super.setText(newText);
		} else {
			Runnable runnable = new FadeInFadeOutRunnable(newText);
			executor.execute(runnable);
		}
	}

	
	private final class FadeInFadeOutRunnable implements Runnable {
		private final String newText;

		private FadeInFadeOutRunnable(String newText) {
			this.newText = newText;
		}

		@Override
		public void run() {
			String oldText = getText();
			if (!oldText.equals(" ")) {
				fadeOut();

				// Wait a bit longer before the new value fades in
				try {
					Thread.sleep(150);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			SetTextWithAnimationLabel.super.setText(newText);
			
			if (!newText.equals(" ")) {
				fadeIn();
			}
		}

		private void fadeOut() {
			Color foreground = getForeground();
			for (int alpha = 255; alpha > 0; alpha -= 5) {
				try {
					Thread.sleep(4);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				Color transparentForeground = new Color(foreground.getRed(), 
						foreground.getGreen(), foreground.getBlue(), alpha);
		
				setForeground(transparentForeground);
			}
		}

		private void fadeIn() {
			Color foreground = getForeground();
			for (int alpha = 0; alpha <= 255; alpha += 5) {
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				Color transparentForeground = new Color(foreground.getRed(), 
						foreground.getGreen(), foreground.getBlue(), alpha);

				setForeground(transparentForeground);
			}
		}
	}
	

}
